import React, { useEffect, useRef } from 'react';
import { Card, Table, Typography, Row, Col, Statistic } from 'antd';
import * as echarts from 'echarts';

const { Title, Text } = Typography;

// 生成过去7天的日期
const generateDates = (days = 7) => {
  const dates = [];
  for (let i = days - 1; i >= 0; i--) {
    const date = new Date();
    date.setDate(date.getDate() - i);
    dates.push(date.toISOString().split('T')[0]);
  }
  return dates;
};

const dates = generateDates();

// 模拟数据
const deviceTypeData = [
  { device_type: '移动端', user_count: 38500, percentage: 68.4 },
  { device_type: '桌面端', user_count: 16500, percentage: 29.4 },
  { device_type: '平板端', user_count: 1200, percentage: 2.1 },
  { device_type: '其他', user_count: 50, percentage: 0.1 },
];

const osData = [
  { os: 'Android', user_count: 22000, percentage: 39.1 },
  { os: 'iOS', user_count: 16500, percentage: 29.4 },
  { os: 'Windows', user_count: 13500, percentage: 24.1 },
  { os: 'macOS', user_count: 3000, percentage: 5.3 },
  { os: '其他', user_count: 1200, percentage: 2.1 },
];

const browserData = [
  { browser: '微信内置浏览器', user_count: 15000, percentage: 26.7 },
  { browser: 'Chrome', user_count: 14500, percentage: 25.8 },
  { browser: 'Safari', user_count: 10000, percentage: 17.9 },
  { browser: 'Alipay内置浏览器', user_count: 8500, percentage: 15.1 },
  { browser: 'Firefox', user_count: 3500, percentage: 6.2 },
  { browser: '其他', user_count: 5800, percentage: 10.3 },
];

// 设备类型趋势数据
const deviceTrendData = [
  ...dates.map(date => ({ date, device_type: '移动端', user_count: Math.floor(Math.random() * 2000) + 5000 })),
  ...dates.map(date => ({ date, device_type: '桌面端', user_count: Math.floor(Math.random() * 1000) + 2000 })),
  ...dates.map(date => ({ date, device_type: '平板端', user_count: Math.floor(Math.random() * 200) + 150 })),
];

// 详细设备信息
const detailedDeviceData = [
  { device_type: '移动端', os: 'Android', browser: '微信内置浏览器', user_count: 8500, avg_session_time: 25, avg_page_views: 4.2 },
  { device_type: '移动端', os: 'Android', browser: 'Chrome', user_count: 5500, avg_session_time: 28, avg_page_views: 4.8 },
  { device_type: '移动端', os: 'Android', browser: 'Alipay内置浏览器', user_count: 4500, avg_session_time: 20, avg_page_views: 3.5 },
  { device_type: '移动端', os: 'Android', browser: '其他', user_count: 3500, avg_session_time: 22, avg_page_views: 3.8 },
  { device_type: '移动端', os: 'iOS', browser: 'Safari', user_count: 6500, avg_session_time: 32, avg_page_views: 5.1 },
  { device_type: '移动端', os: 'iOS', browser: '微信内置浏览器', user_count: 6500, avg_session_time: 26, avg_page_views: 4.3 },
  { device_type: '移动端', os: 'iOS', browser: 'Alipay内置浏览器', user_count: 3500, avg_session_time: 21, avg_page_views: 3.6 },
  { device_type: '桌面端', os: 'Windows', browser: 'Chrome', user_count: 8500, avg_session_time: 45, avg_page_views: 6.8 },
  { device_type: '桌面端', os: 'Windows', browser: 'Firefox', user_count: 3000, avg_session_time: 40, avg_page_views: 6.2 },
  { device_type: '桌面端', os: 'Windows', browser: '其他', user_count: 2000, avg_session_time: 38, avg_page_views: 5.8 },
  { device_type: '桌面端', os: 'macOS', browser: 'Chrome', user_count: 1500, avg_session_time: 48, avg_page_views: 7.1 },
  { device_type: '桌面端', os: 'macOS', browser: 'Safari', user_count: 1500, avg_session_time: 50, avg_page_views: 7.3 },
  { device_type: '平板端', os: 'iOS', browser: 'Safari', user_count: 600, avg_session_time: 35, avg_page_views: 5.5 },
  { device_type: '平板端', os: 'Android', browser: 'Chrome', user_count: 400, avg_session_time: 32, avg_page_views: 5.1 },
  { device_type: '平板端', os: '其他', browser: '其他', user_count: 200, avg_session_time: 30, avg_page_views: 4.8 },
];

// 定义表格列
const columns = [
  {
    title: '设备类型',
    dataIndex: 'device_type',
    key: 'device_type',
  },
  {
    title: '操作系统',
    dataIndex: 'os',
    key: 'os',
  },
  {
    title: '浏览器',
    dataIndex: 'browser',
    key: 'browser',
  },
  {
    title: '用户数量',
    dataIndex: 'user_count',
    key: 'user_count',
  },
  {
    title: '平均会话时长(分钟)',
    dataIndex: 'avg_session_time',
    key: 'avg_session_time',
  },
  {
    title: '平均页面浏览数',
    dataIndex: 'avg_page_views',
    key: 'avg_page_views',
  },
];

const UserDeviceStats = () => {
  const devicePieRef = useRef(null);
  const osBarRef = useRef(null);
  const browserPieRef = useRef(null);
  const trendLineRef = useRef(null);
  
  const devicePieInstance = useRef(null);
  const osBarInstance = useRef(null);
  const browserPieInstance = useRef(null);
  const trendLineInstance = useRef(null);

  useEffect(() => {
    // 初始化图表实例
    if (devicePieRef.current && !devicePieInstance.current) {
      devicePieInstance.current = echarts.init(devicePieRef.current);
    }
    if (osBarRef.current && !osBarInstance.current) {
      osBarInstance.current = echarts.init(osBarRef.current);
    }
    if (browserPieRef.current && !browserPieInstance.current) {
      browserPieInstance.current = echarts.init(browserPieRef.current);
    }
    if (trendLineRef.current && !trendLineInstance.current) {
      trendLineInstance.current = echarts.init(trendLineRef.current);
    }

    // 准备设备类型饼图数据
    const devicePieData = deviceTypeData.map(item => ({
      name: item.device_type,
      value: item.user_count
    }));

    // 准备操作系统柱状图数据
    const osNames = osData.map(item => item.os);
    const osUserCounts = osData.map(item => item.user_count);

    // 准备浏览器饼图数据
    const browserPieData = browserData.map(item => ({
      name: item.browser,
      value: item.user_count
    }));

    // 准备趋势图数据
    const deviceTypes = ['移动端', '桌面端', '平板端'];
    const trendSeries = deviceTypes.map(type => ({
      name: type,
      type: 'line',
      smooth: true,
      data: dates.map(date => {
        const item = deviceTrendData.find(d => d.date === date && d.device_type === type);
        return item ? item.user_count : 0;
      })
    }));

    // 设备类型饼图配置
    const devicePieOption = {
      title: {
        text: '设备类型分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: deviceTypeData.map(item => item.device_type)
      },
      series: [
        {
          name: '设备类型',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 20,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: devicePieData
        }
      ]
    };

    // 操作系统柱状图配置
    const osBarOption = {
      title: {
        text: '操作系统分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: osNames
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: osUserCounts,
          type: 'bar',
          itemStyle: {
            color: function(params) {
              const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de'];
              return colors[params.dataIndex % colors.length];
            }
          },
          label: {
            show: true,
            position: 'top',
            formatter: '{c}'
          }
        }
      ]
    };

    // 浏览器饼图配置
    const browserPieOption = {
      title: {
        text: '浏览器分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: browserData.map(item => item.browser)
      },
      series: [
        {
          name: '浏览器',
          type: 'pie',
          radius: '50%',
          data: browserPieData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };

    // 趋势图配置
    const trendLineOption = {
      title: {
        text: '设备类型使用趋势（最近7天）',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: deviceTypes,
        bottom: 10
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: dates
      },
      yAxis: {
        type: 'value'
      },
      series: trendSeries
    };

    // 渲染图表
    if (devicePieInstance.current) {
      devicePieInstance.current.setOption(devicePieOption);
    }
    if (osBarInstance.current) {
      osBarInstance.current.setOption(osBarOption);
    }
    if (browserPieInstance.current) {
      browserPieInstance.current.setOption(browserPieOption);
    }
    if (trendLineInstance.current) {
      trendLineInstance.current.setOption(trendLineOption);
    }

    // 响应式调整
    const handleResize = () => {
      if (devicePieInstance.current) devicePieInstance.current.resize();
      if (osBarInstance.current) osBarInstance.current.resize();
      if (browserPieInstance.current) browserPieInstance.current.resize();
      if (trendLineInstance.current) trendLineInstance.current.resize();
    };

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
      if (devicePieInstance.current) devicePieInstance.current.dispose();
      if (osBarInstance.current) osBarInstance.current.dispose();
      if (browserPieInstance.current) browserPieInstance.current.dispose();
      if (trendLineInstance.current) trendLineInstance.current.dispose();
    };
  }, []);

  // 计算统计信息
  const totalUsers = deviceTypeData.reduce((sum, item) => sum + item.user_count, 0);
  const maxDeviceType = deviceTypeData.reduce((prev, current) => 
    prev.user_count > current.user_count ? prev : current
  );
  const maxOS = osData.reduce((prev, current) => 
    prev.user_count > current.user_count ? prev : current
  );
  const maxBrowser = browserData.reduce((prev, current) => 
    prev.user_count > current.user_count ? prev : current
  );

  return (
    <div>
      <Title level={4}>用户设备统计分析</Title>
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={8}>
          <Card>
            <Title level={5}>统计概览</Title>
            <Row gutter={16}>
              <Col span={12}>
                <Statistic 
                  title="总用户数" 
                  value={totalUsers}
                  precision={0}
                  valueStyle={{ color: '#3f8600' }}
                />
              </Col>
              <Col span={12}>
                <Statistic 
                  title="移动端占比" 
                  value={deviceTypeData.find(d => d.device_type === '移动端')?.percentage || 0}
                  precision={1}
                  suffix="%"
                  valueStyle={{ color: '#cf1322' }}
                />
              </Col>
              <Col span={12}>
                <Statistic 
                  title="桌面端占比" 
                  value={deviceTypeData.find(d => d.device_type === '桌面端')?.percentage || 0}
                  precision={1}
                  suffix="%"
                  valueStyle={{ color: '#1890ff' }}
                />
              </Col>
              <Col span={12}>
                <Statistic 
                  title="平板端占比" 
                  value={deviceTypeData.find(d => d.device_type === '平板端')?.percentage || 0}
                  precision={1}
                  suffix="%"
                  valueStyle={{ color: '#faad14' }}
                />
              </Col>
            </Row>
            <div style={{ marginTop: 20 }}>
              <div style={{ marginBottom: 10 }}>
                <Text strong>主要设备类型: </Text>
                {maxDeviceType.device_type} ({maxDeviceType.percentage}%)
              </div>
              <div style={{ marginBottom: 10 }}>
                <Text strong>主要操作系统: </Text>
                {maxOS.os} ({maxOS.percentage}%)
              </div>
              <div>
                <Text strong>主要浏览器: </Text>
                {maxBrowser.browser} ({maxBrowser.percentage}%)
              </div>
            </div>
          </Card>
        </Col>
        <Col xs={24} lg={8}>
          <Card>
            <div ref={devicePieRef} style={{ width: '100%', height: 300 }} />
          </Card>
        </Col>
        <Col xs={24} lg={8}>
          <Card>
            <div ref={browserPieRef} style={{ width: '100%', height: 300 }} />
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card>
            <div ref={osBarRef} style={{ width: '100%', height: 300 }} />
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card>
            <div ref={trendLineRef} style={{ width: '100%', height: 300 }} />
          </Card>
        </Col>
      </Row>
      <Card style={{ marginTop: 20 }}>
        <Title level={5}>详细设备信息列表</Title>
        <Table columns={columns} dataSource={detailedDeviceData} rowKey={(record) => `${record.device_type}-${record.os}-${record.browser}`} pagination={{ pageSize: 10 }} />
      </Card>
    </div>
  );
};

export default UserDeviceStats;